package org.clockworkmages.games.anno1186.scripting.tools;

import java.util.ArrayList;
import java.util.List;

public class TextBuilder implements BuilderWrapper {

	private List<ScriptBuilder> conditionScriptBuilders = new ArrayList<ScriptBuilder>();

	private List<String> conditionalTexts = new ArrayList<String>();

	private String defaultText;

	public static TextBuilder NEW() {
		return new TextBuilder();
	}

	@Override
	public ScriptBuilder iff() {
		ScriptBuilder scriptBuilder = new ScriptBuilder(this);
		this.conditionScriptBuilders.add(scriptBuilder);
		return scriptBuilder;
	}

	@Override
	public void then(String s) {
		conditionalTexts.add(s);
	}

	@Override
	public void elsee(String s) {
		defaultText = s;
	}

	@Override
	public ScriptBuilder elseIf() {
		ScriptBuilder scriptBuilder = new ScriptBuilder(this);
		this.conditionScriptBuilders.add(scriptBuilder);
		return scriptBuilder;
	}

	public String toString() {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < conditionScriptBuilders.size(); i++) {
			ScriptBuilder conditionScriptBuilder = conditionScriptBuilders
					.get(i);
			String conditionalText = conditionalTexts.get(i);
			sb.append(i == 0 ? "${if" : "${elseif").append(" ")
					.append(conditionScriptBuilder.toString()).append("}")
					.append(conditionalText);
		}
		if (defaultText != null) {
			sb.append("${else}").append(defaultText);
		}
		sb.append("${fi}");
		return sb.toString();
	}

}
